﻿using Business.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WF_Business;

public partial class UserControls_JqueryDataGrid : System.Web.UI.UserControl
{
    /// <summary>
    /// 关联的表名
    /// </summary>
    public string TableName
    {
        get
        {
            return ViewState["TableName"] as string;
        }
        set
        {
            ViewState["TableName"] = value;
        }
    }

    /// <summary>
    /// 显示对应的字段
    /// </summary>
    public string AppearColumnNames
    {
        get
        {
            return ViewState["AppearColumnNames"] as string;
        }
        set
        {
            ViewState["AppearColumnNames"] = value;
        }
    }

    /// <summary>
    /// 查询条件
    /// </summary>
    public string QueryWhere
    {
        get
        {
            return ViewState["QueryWhere"] as string;
        }
        set
        {
            ViewState["QueryWhere"] = value;
        }
    }

    /// <summary>
    /// 单页显示最大行数
    /// </summary>
    public String PageSize
    {
        get
        {
            if (ViewState["PageSize"] != null)
            {
                return ViewState["PageSize"] as string;
            }
            else
            {
                return "10";//默认展示10行
            }
        }
        set
        {
            ViewState["PageSize"] = value;
        }
    }

    /// <summary>
    /// 列表标题头
    /// </summary>
    public String DgTitle
    {
        get
        {
            return ViewState["DgTitle"] as string;
        }
        set
        {
            ViewState["DgTitle"] = value;
        }
    }

    /// <summary>
    /// 自定义完整的SQL语句，与tabname、appearColumnsName互斥
    /// </summary>
    public String PostSql
    {
        get
        {
            if (ViewState["PostSql"] != null)
            {
                return ViewState["PostSql"] as string;
            }
            else
            {
                return string.Empty;
            }
        }
        set
        {
            ViewState["PostSql"] = value;
        }
    }

    /// <summary>
    /// 跟列属性一样，但是这些列固定在左边，不会滚动。
    /// </summary>
    public String frozenColumnsName
    {
        get
        {
            if (ViewState["frozenColumnsName"] != null)
            {
                return ViewState["frozenColumnsName"] as string;
            }
            else
            {
                return string.Empty;
            }
        }
        set
        {
            ViewState["frozenColumnsName"] = value;
        }
    }

    /// <summary>
    /// 自定义列名
    /// </summary>
    public String AddFormatterColumnNames
    {
        get
        {
            if (ViewState["AddFormatterColumnNames"] != null)
            {
                return ViewState["AddFormatterColumnNames"] as string;
            }
            else
            {
                return string.Empty;
            }
        }
        set
        {
            ViewState["AddFormatterColumnNames"] = value;
        }
    }

    /// <summary>
    /// 自定义列的格式化内容,例如<a href="#">test</a>
    /// </summary>
    public String AddFormatterContent
    {
        get
        {
            return ViewState["AddFormatterContent"] as string;
        }
        set
        {
            ViewState["AddFormatterContent"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindCommonData();
        }
    }

    private void BindCommonData()
    {
        string strVarScript = @"var queryUrl='../UserControls/JqueryDataGridHandler.ashx?flag=1';";
        string strContentScriptStart = @"function ShowTable(){
            $('#tabResult').datagrid({
                url: queryUrl, toolbar: '#tabTools',selectOnCheck:true,checkOnSelect:true,
                editable: false,loadMsg:'正在读取数据...',pageList:[definePs,definePs*2,definePs*3,definePs*4,definePs*5],
                width:'auto',height:'auto',pagination:true,rownumbers:true,collapsible:true, pageSize:definePs,";
        string strContentScriptEnd = @"});
            var p = $('#tabResult').datagrid('getPager');
			$(p).pagination({
				displayMsg:'总共{total}条',beforePageText:'第',afterPageText:'页,共{pages}页'
			});
        }";

//        string strToolBar=@"$('#tabResult').datagrid({
//	            toolbar: [{
//		            iconCls: 'icon-ok',
//		            handler: function(){alert('全选')}
//	            },'-',{
//		            iconCls: 'icon-redo',
//		            handler: function(){bsuExportCsv('help')}
//	            }]
//            });";

        //定义传递参数
        strVarScript += string.Format("var paramInfo = \"&tabName={0}&colNames={1}&queryWhere={2}&postSql={3}\";queryUrl = queryUrl+paramInfo;", TableName, Server.UrlEncode(AppearColumnNames), Server.UrlEncode(QueryWhere), Server.UrlEncode(PostSql));

        //定义页面显示记录数
        strVarScript += string.Format("var definePs={0};", PageSize);

        if (!string.IsNullOrEmpty(DgTitle))
        {
            strContentScriptStart +=string.Format("title:'{0}',",DgTitle);
        }
        if (!string.IsNullOrEmpty(frozenColumnsName))
        {
            if (frozenColumnsName.Contains(AddFormatterColumnNames))
            {
                //AddFormatterContent必须按照如下格式（value是单元格的值）：<a href=test.aspx?id='+value+'>'+value+'</a>
                strContentScriptStart += "frozenColumns:[[{" + frozenColumnsName + ",width:100,formatter:function(value,row,index){return '" + AddFormatterContent + "';}}]],";
            }
            else//不包含在自定义列种则直接显示
            {
                strContentScriptStart += "frozenColumns:[[{"+frozenColumnsName+",width:80}}]],";
            }
        }

        //组建显示sql
        string script = "<script>" + strVarScript + strContentScriptStart + GenColumnsInfo() + strContentScriptEnd + "</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptGrid", script);
    }

    /// <summary>
    /// 生成列头信息
    /// </summary>
    /// <returns></returns>
    private string GenColumnsInfo()
    {
        StringBuilder sb = new StringBuilder();

        DataTable dtSource = new DataTable();
        if (!string.IsNullOrEmpty(PostSql))
        {
            SysParams.OAConnection().RunSql(PostSql, out dtSource);
        }
        else
        {
            OracleSystemOperation osoTemp = new OracleSystemOperation();
            dtSource = osoTemp.GetDataByCommonParams(TableName, AppearColumnNames, QueryWhere);
        }


        if (dtSource != null && dtSource.Rows.Count > 0)
        {
            sb.Append("columns:[[");
            for (int i = 0; i < dtSource.Columns.Count; i++)
            {
                string strColName = dtSource.Columns[i].ColumnName;

                if (frozenColumnsName.Contains(strColName))
                {
                    continue;
                }

                sb.Append("{ field: '" + strColName + "', title: '" + strColName + "',sortable:true,resizable:true,align:'center',sortOrder:'asc'");

                if (AddFormatterColumnNames.Contains(strColName))
                {
                    //AddFormatterContent必须按照如下格式（value是单元格的值）：<a href=test.aspx?id='+value+'>'+value+'</a>
                    sb.Append(", width:100,formatter:function(value,row,index){return '" + AddFormatterContent + "';}");
                }
                else
                {
                    sb.Append(", width:100");
                }

                sb.Append("}");
                if (i != dtSource.Columns.Count - 1)
                {
                    sb.Append(",");
                }
            }
            sb.Append("]]");
        }
        return sb.ToString();
    }

}